<template>
  <div class="cameras-container">
    <el-card class="camera-card">
      <template #header>
        <div class="card-header">
          <span>摄像头监控管理</span>
          <el-button type="primary" @click="showAddCameraDialog = true">添加摄像头</el-button>
        </div>
      </template>
      
      <div class="camera-grid">
        <el-card 
          v-for="camera in cameras" 
          :key="camera.id" 
          class="camera-item-card"
        >
          <div class="camera-item-header">
            <h3>{{ camera.name }}</h3>
            <div class="camera-status" :class="camera.status">
              {{ camera.status === 'online' ? '在线' : '离线' }}
            </div>
          </div>
          
          <div class="camera-preview">
            <img :src="camera.preview_url || 'https://via.placeholder.com/300x200?text=Camera+Preview'" alt="Camera Preview" />
          </div>
          
          <div class="camera-info">
            <p><strong>位置:</strong> {{ camera.location || '未设置' }}</p>
            <p><strong>IP地址:</strong> {{ camera.ip_address }}</p>
            <p><strong>分辨率:</strong> {{ camera.resolution || '未设置' }}</p>
            <p v-if="camera.status === 'online'" class="camera-detection-status">
              <span class="detection-label" :class="camera.detection_enabled ? 'enabled' : 'disabled'">
                {{ camera.detection_enabled ? '检测已启用' : '检测未启用' }}
              </span>
            </p>
          </div>
          
          <div class="camera-actions">
            <el-button type="primary" size="small" @click="viewCameraStream(camera)">查看视频</el-button>
            <el-button type="success" size="small" :disabled="camera.status === 'online'" @click="startCamera(camera.id)">启动</el-button>
            <el-button type="danger" size="small" :disabled="camera.status === 'offline'" @click="stopCamera(camera.id)">停止</el-button>
            <el-button type="warning" size="small" @click="editCamera(camera)">编辑</el-button>
            <el-button type="info" size="small" @click="getCameraStats(camera.id)">统计</el-button>
          </div>
        </el-card>
      </div>
      
      <!-- 摄像头添加对话框 -->
      <el-dialog v-model="showAddCameraDialog" title="添加摄像头" width="500px">
        <el-form :model="cameraForm" :rules="cameraRules" ref="cameraFormRef">
          <el-form-item label="摄像头名称" prop="name">
            <el-input v-model="cameraForm.name" placeholder="请输入摄像头名称"></el-input>
          </el-form-item>
          <el-form-item label="IP地址" prop="ip_address">
            <el-input v-model="cameraForm.ip_address" placeholder="请输入IP地址"></el-input>
          </el-form-item>
          <el-form-item label="位置">
            <el-input v-model="cameraForm.location" placeholder="请输入摄像头位置"></el-input>
          </el-form-item>
          <el-form-item label="分辨率">
            <el-select v-model="cameraForm.resolution">
              <el-option label="720p" value="720p"></el-option>
              <el-option label="1080p" value="1080p"></el-option>
              <el-option label="4K" value="4K"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用检测" prop="detection_enabled">
            <el-switch v-model="cameraForm.detection_enabled"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAddCameraDialog = false">取消</el-button>
            <el-button type="primary" @click="addCamera">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 摄像头编辑对话框 -->
      <el-dialog v-model="showEditCameraDialog" title="编辑摄像头" width="500px">
        <el-form :model="cameraForm" :rules="cameraRules" ref="cameraFormRef">
          <el-form-item label="摄像头名称" prop="name">
            <el-input v-model="cameraForm.name" placeholder="请输入摄像头名称"></el-input>
          </el-form-item>
          <el-form-item label="IP地址" prop="ip_address">
            <el-input v-model="cameraForm.ip_address" placeholder="请输入IP地址"></el-input>
          </el-form-item>
          <el-form-item label="位置">
            <el-input v-model="cameraForm.location" placeholder="请输入摄像头位置"></el-input>
          </el-form-item>
          <el-form-item label="分辨率">
            <el-select v-model="cameraForm.resolution">
              <el-option label="720p" value="720p"></el-option>
              <el-option label="1080p" value="1080p"></el-option>
              <el-option label="4K" value="4K"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用检测" prop="detection_enabled">
            <el-switch v-model="cameraForm.detection_enabled"></el-switch>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showEditCameraDialog = false">取消</el-button>
            <el-button type="primary" @click="updateCamera">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 摄像头视频流查看对话框 -->
      <el-dialog v-model="showCameraStreamDialog" :title="selectedCamera?.name + ' - 视频监控'" width="800px" fullscreen>
        <div class="camera-stream-container">
          <div class="stream-controls">
            <el-checkbox v-model="showDetectionOverlay" @change="toggleDetection">显示检测框</el-checkbox>
            <el-checkbox v-model="showDetectionLabels" :disabled="!showDetectionOverlay">显示标签</el-checkbox>
            <el-switch v-model="realTimeStats" active-text="实时统计" inactive-text="关闭统计"></el-switch>
            <el-button type="primary" size="small" @click="captureSnapshot">截图</el-button>
          </div>
          
          <div class="video-container">
            <!-- 视频流和检测覆盖层 -->
            <div class="video-wrapper">
              <img :src="cameraStreamUrl" alt="Camera Stream" class="camera-stream" />
              <!-- 检测框覆盖层 -->
              <div v-if="showDetectionOverlay && currentDetections.length > 0" class="detection-overlay">
                <div
                  v-for="(detection, index) in currentDetections"
                  :key="index"
                  class="detection-box"
                  :style="{
                    left: detection.x + 'px',
                    top: detection.y + 'px',
                    width: detection.width + 'px',
                    height: detection.height + 'px',
                    borderColor: getBoxColor(detection.class_name)
                  }"
                >
                  <span 
                    v-if="showDetectionLabels"
                    class="detection-label"
                    :style="{ backgroundColor: getBoxColor(detection.class_name) }"
                  >
                    {{ getClassNameCN(detection.class_name) }} ({{ Math.round(detection.confidence * 100) }}%)
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 实时统计面板 -->
          <div v-if="realTimeStats" class="realtime-stats-panel">
            <h4>实时检测统计</h4>
            <div class="realtime-stats-grid">
              <el-statistic 
                v-for="(count, class_name) in detectionStats" 
                :key="class_name"
                class="realtime-stat-item"
                :title="getClassNameCN(class_name)"
                :value="count"
                :value-style="{ color: getBoxColor(class_name) }"
              />
            </div>
            <div v-if="Object.keys(detectionStats).length === 0" class="no-detections">
              暂无检测目标
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCameraStreamDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 摄像头统计信息对话框 -->
      <el-dialog v-model="showCameraStatsDialog" :title="selectedCamera?.name + ' - 统计信息'" width="600px">
        <div v-if="cameraStats" class="camera-stats">
          <h3>实时统计数据</h3>
          <div class="stats-grid">
            <el-statistic :title="'总检测数'" :value="cameraStats.total_detections || 0" />
            <el-statistic :title="'行人数量'" :value="cameraStats.person_count || 0" :value-style="{ color: '#ff4d4f' }" />
            <el-statistic :title="'车辆数量'" :value="cameraStats.vehicle_count || 0" :value-style="{ color: '#1890ff' }" />
            <el-statistic :title="'头盔佩戴率'" :value="cameraStats.helmet_rate || 0" suffix="%" :precision="1" :value-style="{ color: '#52c41a' }" />
          </div>
          
          <h3 class="mt-4">最近告警</h3>
          <el-list v-if="cameraStats.recent_alerts && cameraStats.recent_alerts.length > 0">
            <el-list-item v-for="alert in cameraStats.recent_alerts" :key="alert.id">
              <span>{{ alert.timestamp }} - {{ alert.message }}</span>
            </el-list-item>
          </el-list>
          <div v-else class="no-data">暂无告警记录</div>
        </div>
        <div v-else class="loading-stats">加载统计数据中...</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCameraStatsDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'Cameras',
  setup() {
    // 状态管理
    const cameras = ref([])
    const showAddCameraDialog = ref(false)
    const showEditCameraDialog = ref(false)
    const showCameraStreamDialog = ref(false)
    const showCameraStatsDialog = ref(false)
    const selectedCamera = ref(null)
    const cameraStreamUrl = ref('')
    const cameraStats = ref(null)
    
    // 视频流检测相关状态
    const showDetectionOverlay = ref(true)
    const showDetectionLabels = ref(true)
    const realTimeStats = ref(true)
    const currentDetections = ref([])
    const detectionUpdateInterval = ref(null)
    
    // 摄像头表单
    const cameraForm = ref({
      id: null,
      name: '',
      ip_address: '',
      location: '',
      resolution: '720p',
      status: 'offline',
      detection_enabled: true // 默认启用检测
    })
    
    // 表单验证规则
    const cameraRules = ref({
      name: [{ required: true, message: '请输入摄像头名称', trigger: 'blur' }],
      ip_address: [{ required: true, message: '请输入IP地址', trigger: 'blur' }]
    })
    
    // 表单引用
    const cameraFormRef = ref(null)
    
    // 检测结果统计
    const detectionStats = computed(() => {
      const stats = {}
      currentDetections.value.forEach(detection => {
        const className = detection.class_name
        stats[className] = (stats[className] || 0) + 1
      })
      return stats
    })
    
    // 获取摄像头列表
    const fetchCameras = async () => {
      try {
        // 模拟API调用
        const mockCameras = getMockCameras()
        cameras.value = mockCameras
      } catch (error) {
        console.error('获取摄像头列表失败:', error)
        ElMessage.error('获取摄像头列表失败')
      }
    }
    
    // 模拟摄像头数据
    const getMockCameras = () => {
      return [
        {
          id: 1,
          name: '前门摄像头',
          ip_address: '192.168.1.101',
          location: '前门入口',
          resolution: '1080p',
          status: 'online',
          detection_enabled: true,
          preview_url: 'https://via.placeholder.com/300x200?text=Front+Door'
        },
        {
          id: 2,
          name: '停车场摄像头',
          ip_address: '192.168.1.102',
          location: '地下停车场',
          resolution: '720p',
          status: 'online',
          detection_enabled: true,
          preview_url: 'https://via.placeholder.com/300x200?text=Parking+Lot'
        },
        {
          id: 3,
          name: '后门摄像头',
          ip_address: '192.168.1.103',
          location: '后门出口',
          resolution: '1080p',
          status: 'offline',
          detection_enabled: false,
          preview_url: 'https://via.placeholder.com/300x200?text=Back+Door'
        },
        {
          id: 4,
          name: '街道监控摄像头',
          ip_address: '192.168.1.104',
          location: '街道',
          resolution: '4K',
          status: 'online',
          detection_enabled: true,
          preview_url: 'https://via.placeholder.com/300x200?text=Street'
        }
      ]
    }
    
    // 添加摄像头
    const addCamera = async () => {
      try {
        // 模拟API调用
        const newCamera = {
          id: Date.now(),
          ...cameraForm.value,
          preview_url: 'https://via.placeholder.com/300x200?text=New+Camera'
        }
        cameras.value.push(newCamera)
        showAddCameraDialog.value = false
        resetCameraForm()
        ElMessage.success('摄像头添加成功')
      } catch (error) {
        console.error('添加摄像头失败:', error)
        ElMessage.error('添加摄像头失败')
      }
    }
    
    // 编辑摄像头
    const editCamera = (camera) => {
      selectedCamera.value = camera
      cameraForm.value = { ...camera }
      showEditCameraDialog.value = true
    }
    
    // 更新摄像头
    const updateCamera = async () => {
      try {
        // 模拟API调用
        const index = cameras.value.findIndex(c => c.id === cameraForm.value.id)
        if (index !== -1) {
          cameras.value[index] = { ...cameraForm.value }
        }
        showEditCameraDialog.value = false
        resetCameraForm()
        ElMessage.success('摄像头更新成功')
      } catch (error) {
        console.error('更新摄像头失败:', error)
        ElMessage.error('更新摄像头失败')
      }
    }
    
    // 启动摄像头
    const startCamera = async (cameraId) => {
      try {
        // 模拟API调用
        const camera = cameras.value.find(c => c.id === cameraId)
        if (camera) {
          camera.status = 'online'
          ElMessage.success(`摄像头 ${camera.name} 启动成功`)
        }
      } catch (error) {
        console.error('启动摄像头失败:', error)
        ElMessage.error('启动摄像头失败')
      }
    }
    
    // 停止摄像头
    const stopCamera = async (cameraId) => {
      try {
        // 模拟API调用
        const camera = cameras.value.find(c => c.id === cameraId)
        if (camera) {
          camera.status = 'offline'
          ElMessage.success(`摄像头 ${camera.name} 停止成功`)
        }
      } catch (error) {
        console.error('停止摄像头失败:', error)
        ElMessage.error('停止摄像头失败')
      }
    }
    
    // 模拟检测数据
    const generateMockDetections = () => {
      const detectionTypes = ['person', 'car', 'bicycle', 'motorcycle', 'truck', 'helmet', 'no_helmet']
      const detections = []
      const count = Math.floor(Math.random() * 5) + 1 // 1-5个检测目标
      
      for (let i = 0; i < count; i++) {
        const type = detectionTypes[Math.floor(Math.random() * detectionTypes.length)]
        detections.push({
          id: i,
          class_name: type,
          confidence: Math.random() * 0.5 + 0.5, // 0.5-1.0的置信度
          x: Math.floor(Math.random() * 600) + 50,
          y: Math.floor(Math.random() * 300) + 50,
          width: Math.floor(Math.random() * 100) + 50,
          height: Math.floor(Math.random() * 100) + 50
        })
      }
      
      return detections
    }
    
    // 更新检测数据
    const updateDetections = () => {
      if (selectedCamera.value && selectedCamera.value.detection_enabled) {
        currentDetections.value = generateMockDetections()
      } else {
        currentDetections.value = []
      }
    }
    
    // 查看摄像头视频流
    const viewCameraStream = (camera) => {
      selectedCamera.value = camera
      // 模拟视频流URL
      cameraStreamUrl.value = `https://via.placeholder.com/800x450?text=Camera+Stream+${camera.id}`
      showCameraStreamDialog.value = true
      
      // 启动检测数据更新
      updateDetections() // 立即更新一次
      detectionUpdateInterval.value = setInterval(updateDetections, 2000) // 每2秒更新一次
    }
    
    // 切换检测显示
    const toggleDetection = () => {
      if (showDetectionOverlay.value) {
        updateDetections()
      } else {
        currentDetections.value = []
      }
    }
    
    // 截图
    const captureSnapshot = () => {
      ElMessage.success('截图成功')
      // 实际项目中这里应该调用后端API来获取当前帧的截图
    }
    
    // 获取摄像头统计信息
    const getCameraStats = async (cameraId) => {
      try {
        selectedCamera.value = cameras.value.find(c => c.id === cameraId)
        // 模拟API调用
        cameraStats.value = {
          total_detections: Math.floor(Math.random() * 1000),
          person_count: Math.floor(Math.random() * 100),
          vehicle_count: Math.floor(Math.random() * 50),
          helmet_rate: Math.floor(Math.random() * 100),
          recent_alerts: [
            { id: 1, timestamp: '2024-01-15 10:30:25', message: '检测到未戴头盔人员' },
            { id: 2, timestamp: '2024-01-15 10:25:10', message: '车辆异常停留' },
            { id: 3, timestamp: '2024-01-15 10:20:30', message: '检测到未戴头盔人员' }
          ]
        }
        showCameraStatsDialog.value = true
      } catch (error) {
        console.error('获取摄像头统计信息失败:', error)
        ElMessage.error('获取摄像头统计信息失败')
      }
    }
    
    // 重置摄像头表单
    const resetCameraForm = () => {
      cameraForm.value = {
        id: null,
        name: '',
        ip_address: '',
        location: '',
        resolution: '720p',
        status: 'offline',
        detection_enabled: true
      }
      if (cameraFormRef.value) {
        cameraFormRef.value.resetFields()
      }
    }
    
    // 获取检测框颜色
    const getBoxColor = (className) => {
      const colorMap = {
        'person': '#ff4d4f',
        'car': '#1890ff',
        'bicycle': '#52c41a',
        'motorcycle': '#faad14',
        'truck': '#722ed1',
        'helmet': '#52c41a',
        'no_helmet': '#ff4d4f'
      }
      return colorMap[className] || '#d9d9d9'
    }
    
    // 获取中文类别名称
    const getClassNameCN = (className) => {
      const nameMap = {
        'person': '行人',
        'car': '汽车',
        'bicycle': '自行车',
        'motorcycle': '摩托车',
        'truck': '货车',
        'helmet': '戴头盔',
        'no_helmet': '未戴头盔'
      }
      return nameMap[className] || className
    }
    
    // 组件挂载时获取摄像头列表
    onMounted(() => {
      fetchCameras()
    })
    
    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (detectionUpdateInterval.value) {
        clearInterval(detectionUpdateInterval.value)
      }
    })
    
    return {
      cameras,
      showAddCameraDialog,
      showEditCameraDialog,
      showCameraStreamDialog,
      showCameraStatsDialog,
      selectedCamera,
      cameraStreamUrl,
      cameraStats,
      cameraForm,
      cameraRules,
      cameraFormRef,
      showDetectionOverlay,
      showDetectionLabels,
      realTimeStats,
      currentDetections,
      detectionStats,
      fetchCameras,
      addCamera,
      editCamera,
      updateCamera,
      startCamera,
      stopCamera,
      viewCameraStream,
      toggleDetection,
      captureSnapshot,
      getCameraStats,
      resetCameraForm,
      getBoxColor,
      getClassNameCN
    }
  }
}
</script>

<style scoped>
.cameras-container {
  padding: 20px;
}

.camera-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.camera-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.camera-item-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.camera-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.camera-item-header h3 {
  margin: 0;
  font-size: 16px;
}

.camera-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.camera-status.online {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.camera-status.offline {
  background-color: #f5f5f5;
  color: #8c8c8c;
  border: 1px solid #d9d9d9;
}

.camera-detection-status {
  margin: 5px 0;
  font-size: 12px;
}

.detection-label {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.detection-label.enabled {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.detection-label.disabled {
  background-color: #f5f5f5;
  color: #8c8c8c;
  border: 1px solid #d9d9d9;
}

.camera-preview {
  margin-bottom: 10px;
  text-align: center;
}

.camera-preview img {
  max-width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.camera-info {
  margin-bottom: 10px;
  font-size: 14px;
}

.camera-info p {
  margin: 5px 0;
}

.camera-actions {
  margin-top: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.camera-stream-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
}

.stream-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  overflow: hidden;
}

.video-wrapper {
  position: relative;
  max-width: 100%;
  max-height: 100%;
}

.camera-stream {
  max-width: 100%;
  max-height: 60vh;
  border-radius: 4px;
  border: 2px solid #e8e8e8;
}

.detection-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.detection-box {
  position: absolute;
  border: 2px solid;
  border-radius: 4px;
  pointer-events: none;
  animation: pulse 1s infinite alternate;
}

@keyframes pulse {
  from { opacity: 0.7; }
  to { opacity: 1; }
}

.detection-label {
  position: absolute;
  top: -20px;
  left: 0;
  padding: 2px 8px;
  font-size: 12px;
  color: white;
  border-radius: 2px;
  white-space: nowrap;
  font-weight: 500;
}

.realtime-stats-panel {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.realtime-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 10px;
}

.realtime-stat-item {
  background-color: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.no-detections {
  text-align: center;
  padding: 20px;
  color: #8c8c8c;
  font-style: italic;
}

.camera-stats {
  padding: 10px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin: 20px 0;
}

.loading-stats {
  text-align: center;
  padding: 20px;
  color: #8c8c8c;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #8c8c8c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 16px;
}
</style>